//
//  BN_SettingViewController.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-5-24.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_SettingViewController.h"

#define PATH_DOC_USERDATA [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"UserData"]

@interface BN_SettingViewController () {
    NSArray *itemNameArr_;
    NSString *newVersionUrl_;
    
    __weak BN_PersonalModifyTextInfo *currentCell_;
    BN_MyInfoHelper *myInfoHelper_;
}

@end

@implementation BN_SettingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (IOS7) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"设置";
    self.view.backgroundColor = APP_OBJECT_GRAY_COLOR;
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"houtui"] style:UIBarButtonItemStylePlain target:self action:@selector(backRootVc)];
    self.navigationItem.leftBarButtonItem = leftItem;

    // UITableView
    self.settingTableView = [[UITableView alloc]init];
    self.settingTableView.delegate = self;
    self.settingTableView.dataSource = self;
    switch (MAIN_VERSION) {
        case 6:
            self.settingTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44);
            break;
        default:
            self.settingTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, FULLSCREEN_HEIGHT);
            self.settingTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            self.settingTableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 0, 0);
            break;
    }
    
    if ([self.settingTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.settingTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    [self setExtraCellLineHidden:self.settingTableView];
    self.settingTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    self.settingTableView.backgroundColor = APP_OBJECT_GRAY_COLOR;
    self.settingTableView.showsVerticalScrollIndicator = NO;                               
    [self.view addSubview:self.settingTableView];
    // NSObject
    itemNameArr_ = @[@"修改密码",@"绑定邮箱",@"清除图片缓存",@"检查新版本",@"意见反馈",@"使用协议",@"关于宝宝在干嘛",@"退出登录"];
    
    // helper
    myInfoHelper_ = [[BN_MyInfoHelper alloc]init];
    [self performSelectorInBackground:@selector(requestNetData) withObject:nil];
}

#pragma mark
#pragma mark UITableView Delegate|DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSInteger rowCount = 0;
    switch (section) {
        case 0:
            rowCount = 2;
            break;
        case 1:
            rowCount = 5;
            break;
        case 2:
            rowCount = 1;
            break;
        default:
            break;
    }
    return rowCount;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    headerView.backgroundColor = APP_OBJECT_GRAY_COLOR;
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"BN_PersonalModifyTextInfo";
    BN_PersonalModifyTextInfo *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"BN_PersonalModifyTextInfo" owner:nil options:nil]objectAtIndex:0];
    }
    cell.fieldsName.frame = CGRectMake(20, 12, 150, 21);
    switch (indexPath.section) {
        case 0:
            cell.fieldsName.text = itemNameArr_[indexPath.row];
            break;
        case 1:
            cell.fieldsName.text = itemNameArr_[indexPath.row+2];
            break;
        case 2:
            cell.fieldsName.text = itemNameArr_[indexPath.row+7];
            break;
        default:
            break;
    }
    
    if (indexPath.row == 1 && indexPath.section == 0) {
        cell.fieldsInfoTextField.enabled = NO;
        if (![self.netDict[@"mail"] isEqual:[NSNull null]]) {
            cell.fieldsInfoTextField.placeholder = self.netDict[@"mail"];
        }else {
            cell.fieldsInfoTextField.placeholder = @"未填写";
        }
    }else {
        [cell.fieldsInfoTextField removeFromSuperview];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 修改密码
    if (indexPath.section == 0 && indexPath.row == 0) {
        BN_Modify_PassWordViewController *modifyPwdVC = [[BN_Modify_PassWordViewController alloc]init];
        [self.navigationController pushViewController:modifyPwdVC animated:YES];
    }
    
    // 清除缓存
    if (indexPath.section == 1 && indexPath.row == 0) {
        UIActionSheet *settingActionSheet = [[UIActionSheet alloc]initWithTitle:@"确定要清除缓存吗？" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"清除缓存" otherButtonTitles:nil, nil];
        settingActionSheet.tag = 501;
        settingActionSheet.actionSheetStyle = UIActionSheetStyleDefault;
        [settingActionSheet showInView:self.view];
    }
    
    // 检查更新
    if (indexPath.section == 1 && indexPath.row == 1) {
        [SVProgressHUD showWithStatus:@"正在检查新版本..." maskType:SVProgressHUDMaskTypeNone];
        [self versionUpDate];
    }
    
    // 意见反馈
    if (indexPath.section == 1 && indexPath.row == 2) {
        BN_FeedBackViewController *feedBackVC = [[BN_FeedBackViewController alloc]init];
        [self.navigationController pushViewController:feedBackVC animated:YES];
    }
    
    // 使用协议
    if (indexPath.section == 1 && indexPath.row == 3) {
        BN_AgreementViewController *agreementVc = [[BN_AgreementViewController alloc]init];
        [self.navigationController pushViewController:agreementVc animated:YES];
    }
    
    // 关于我们
    if (indexPath.section == 1 && indexPath.row == 4) {
        BN_AboutUsViewController *aboutUsVC = [[BN_AboutUsViewController alloc]init];
        [self.navigationController pushViewController:aboutUsVC animated:YES];
    }
    
    // 登出
    if (indexPath.section == 2 && indexPath.row == 0) {
        UIActionSheet *settingActionSheet = [[UIActionSheet alloc]initWithTitle:@"您确定要从宝贝在干嘛退出吗？" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"退出" otherButtonTitles:nil, nil];
        settingActionSheet.tag = 502;
        settingActionSheet.actionSheetStyle = UIActionSheetStyleDefault;
        [settingActionSheet showInView:self.view];
    }
}

#pragma mark
#pragma mark UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (actionSheet.tag) {
        case 501:
        {
            switch (buttonIndex) {
                case 0:
                    [[SDImageCache sharedImageCache] clearDisk];
                    [[SDImageCache sharedImageCache] clearMemory];
                    [LZCHINT title:@"成功清除图片缓存" type:LZCSuccess duration:2 places:HINT_PLACES callBack:NULL];
                    break;
                
                default:
                    break;
            }
        }
            break;
        case 502:
        {
            switch (buttonIndex) {
                case 0:
                {
                    self.navigationController.navigationBarHidden = YES;
                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:FIRSTRUN];
                    [[NSUserDefaults standardUserDefaults]synchronize];
                    NSString *path = [NSString stringWithFormat:@"%@/userPhoto.png",PATH_DOC_USERDATA];
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    [fileManager removeItemAtPath:path error:nil];
                    
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"K_APP_LOGIN" object:nil];
                }
                    break;
                case 1:
                    
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
}

-(void)setExtraCellLineHidden:(UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = APP_OBJECT_GRAY_COLOR;
    [tableView setTableFooterView:view];
}

#pragma mark UIScrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 关闭键盘
    [[NSNotificationCenter defaultCenter]postNotificationName:@"KTEXTINFO_HIDEKEYBOARD" object:nil];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

}

#pragma mark 网络请求
- (void)requestNetData {
    __weak typeof(self) weakSelf = self;
    [myInfoHelper_ queryUserInfo:^(id result, NSString *errMsg) {
        if (errMsg) {
            [LZCHINT title:errMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
        }else{
            weakSelf.netDict = (NSDictionary *)result;
            [weakSelf.settingTableView reloadData];
        }
    }];
}

//检查版本更新
- (void) versionUpDate
{
    // 正式版本
    NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/lookup?id=896421939"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    [request setURL:url];
    [request setHTTPMethod:@"GET"];
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc]init];
    [NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            NSDictionary *respDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSString *resultCount = [NSString stringWithFormat:@"%@",[respDict objectForKey:@"resultCount"]];
            if ([resultCount isEqualToString:@"0"]) {
                [LZCHINT title:@"宝贝在干嘛已是最新版本" type:LZCSuccess duration:2 places:HINT_PLACES callBack:NULL];
            }else {
                NSArray *results = [respDict objectForKey:@"results"];
                NSDictionary *info = [results objectAtIndex:0];
                NSString *newVersion = [info objectForKey:@"version"];
                newVersionUrl_ = [info objectForKey:@"trackViewUrl"];
                NSDictionary *infoDict = [[NSBundle mainBundle]infoDictionary];
                NSString *localVersion = [infoDict objectForKey:@"CFBundleVersion"];
                
                NSComparisonResult result = [newVersion compare:localVersion options:NSNumericSearch];
                if (result == NSOrderedSame||result == NSOrderedAscending) {
                    [LZCHINT title:@"宝贝在干嘛已是最新版本" type:LZCSuccess duration:2 places:HINT_PLACES callBack:NULL];
                }else if (result == NSOrderedDescending){
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle: nil message:@"“宝贝在干嘛”有新版本，是否更新新版本？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    alert.tag = 504;
                    [alert show];
                }
            }
        });
     }];
}

#pragma mark UIAlterView 
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    // 检查版本更新
    if (alertView.tag == 504) {
        if (buttonIndex == 1) {
            UIApplication *application = [UIApplication sharedApplication];
            [application openURL:[NSURL URLWithString:newVersionUrl_]];
        }
    }
}

#pragma mark Action 

- (void)backRootVc {
    [self releaseResource];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 资源
- (void)releaseResource {
    [SVProgressHUD dismiss];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"KTEXTINFO_HIDEKEYBOARD" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"K_APP_LOGIN" object:nil];

    self.settingTableView.delegate = nil;
    self.settingTableView.dataSource = nil;
    self.settingTableView = nil;
}

- (void)dealloc
{
    [self releaseResource];
    NSLog(@"设置 释放...");
}
@end
